<template>
  <HeadContainer :title="$t('title.prefer')" @back="back">
    <form class="gap-col-16">
      <GenderPicker
        v-model="genderPicker.value"
        :err-msg="genderPicker.error"
        :gender="genderValue"
        :interestedIn="interestedValues"
      ></GenderPicker>
      <v-divider></v-divider>
      <div class="mt-4">
        <div class="d-flex gap-row-16">
          <div @click="onSave()" class="primary-btn w-100 d-flex justify-center align-center">
            {{ $t('common.save') }}
          </div>
        </div>
      </div>
      <div
        v-if="setGenderErrMsg"
        class="text-start err-msg font-size-14 font-weight-400 line-height-120 text-primary-x"
      >
        {{ setGenderErrMsg }}
      </div>
    </form>
  </HeadContainer>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { useLocalStorage } from '@vueuse/core'
import { useNavStore } from '@/store/nav'
import { usePopupMessageStore } from '@/store/popup-message'
import { $t } from '@/i18n'
import GenderPicker from '@/components/form/GenderPicker.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import { GENDER, LOCAL_STORAGE_KEYS, NAVS } from '@/constant'
import API from '@/http'

const { open } = usePopupMessageStore()
const navStore = useNavStore()
const { refreshNavs } = navStore

const emits = defineEmits(['back'])
function back() {
  emits('back')
}

const genderPicker = reactive({
  value: {},
  error: '',
})

const initialGenderStorage = useLocalStorage(LOCAL_STORAGE_KEYS.GENDER, GENDER.MALE)
const initialInterestedStorage = useLocalStorage(LOCAL_STORAGE_KEYS.GUEST_INTERESTED_IN, [])

const setGenderErrMsg = ref('')

const genderValue = initialGenderStorage.value
const interestedValues = initialInterestedStorage.value.slice()

function onSave() {
  const data = {
    gender: genderPicker.value.gender,
    interested_in: genderPicker.value.interestedIn.join(','),
  }
  API.Auth.fondness({ data })
    .then(() => {
      initialGenderStorage.value = genderPicker.value.gender
      initialInterestedStorage.value = genderPicker.value.interestedIn
      open($t('common.setSuc'))
      back()
      refreshNavs([NAVS.HOME, NAVS.SEARCH])
    })
    .catch((e) => {
      console.warn(e)
      setGenderErrMsg.value = e.message
    })
}
</script>
